<template>
  <div class="login-page">
    <img id="logo" src="../assets/img/CatWork.png" alt="" oncontextmenu="return false;" ondragstart="return false;"
         style="user-select: none;">
    <div class="form">
      <el-form class="register-form" ref="registerForm" :model="registerForm" :rules="rules">
        <el-form-item prop="enterprise">
          <el-input v-model.trim="registerForm.enterprise" placeholder="请输入你的企业名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="name">
          <el-input v-model.trim="registerForm.name" placeholder="输入你的姓名" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model.trim="registerForm.password" placeholder="输入你的密码" clearable show-password></el-input>
        </el-form-item>
        <el-form-item  prop="checkPass">
          <el-input type="password" v-model="registerForm.checkPass" placeholder="请再次输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model.trim="registerForm.phone" placeholder="输入你的手机号码" clearable></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model.trim="registerForm.email" placeholder="请输入邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item prop="imageCode" class="ImageCodeItem">
          <el-input v-model.trim="registerForm.imageCode" placeholder="请输入结果" clearable class="CodeInput"></el-input>
          <el-tooltip class="item" effect="dark" content="点击更换验证码" placement="right">
            <img :src="codeUrl" @click="getCode" class="ImageCode"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item prop="phoneCode">
          <el-input v-model.trim="registerForm.phoneCode" placeholder="请输入验证码" clearable class="CodeInput"></el-input>
          <el-button  :disabled="!registerForm.show" class="codeButton" @click="getPhoneCode">
            <span v-show="registerForm.show" >发送验证码</span>
            <span v-show="!registerForm.show" class="count">{{registerForm.count}} s后可点击重发</span>
          </el-button>
        </el-form-item>
        <div class="bottom">
          <button style="color: white" type="button" @click="register('registerForm')">注 册</button>
          <p class="message">或 <span @click="loginRes" style="color:white;cursor: pointer">返回登录企业</span></p>
        </div>
      </el-form>
      <el-form class="login-form" ref="loginForm" :model="loginForm" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model.trim="loginForm.username" placeholder="请输入账号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model.trim="loginForm.password" placeholder="请输入密码" clearable show-password></el-input>
        </el-form-item>
        <p class="f-password" @click="centerDialogVisible = true;getCode();">忘记密码？</p>
        <div class="bottom">
          <button style="color: white" type="button" @click="Login('loginForm')">登 录</button>
          <p class="message">或 <span @click="loginRes" style="color:white;cursor: pointer">创建企业</span></p>
        </div>
      </el-form>
    </div>
    <div style="text-align: center">
      <img src="../assets/img/DownCat.png" alt="" class="LoginDownCat">
    </div>
    <el-dialog
            title = "重置密码"
            :modal ="false"
            :visible.sync="centerDialogVisible"
            width="400px"
            :center="true"
            :close-on-click-modal = "false">
      <el-tabs v-model="activeName" @tab-click="getCode">
        <el-tab-pane label="手机验证" name="first">
          <el-form ref="updatePasswordForm" :model="updatePasswordForm" :rules="rules">
            <el-form-item prop="phone">
              <el-input v-model.trim="updatePasswordForm.phone" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
            <el-form-item prop="imageCode" class="ImageCodeItem">
              <el-input v-model.trim="updatePasswordForm.imageCode" placeholder="请输入结果" clearable class="CodeInput1"></el-input>
              <el-tooltip class="item" effect="dark" content="点击更换验证码" placement="right">
                <img :src="codeUrl" @click="getCode" class="ImageCode"/>
              </el-tooltip>
            </el-form-item>
            <el-form-item prop="phoneCode" class="PhoneCodeItem">
              <el-input  v-model.trim="updatePasswordForm.phoneCode" placeholder="请输入验证码" clearable class="CodeInput1"></el-input>
              <el-button  :disabled="!updatePasswordForm.show"  @click="UpdateGetPhoneCode" class="codeButton2">
                <span v-show="updatePasswordForm.show" >发送验证码</span>
                <span v-show="!updatePasswordForm.show" class="count">{{updatePasswordForm.count}} s后可点击重发</span>
              </el-button>
            </el-form-item>
            <el-form-item prop="newPassword">
              <el-input v-model.trim="updatePasswordForm.newPassword" placeholder="请设置新密码" clearable show-password></el-input>
            </el-form-item>
            <el-form-item prop="checkNewPass">
              <el-input v-model.trim="updatePasswordForm.checkNewPass" placeholder="再次输入密码" clearable show-password>></el-input>
            </el-form-item>
          </el-form>
          <div class="footerButton">
            <el-button style="width:200px;" @click="updatePassword('updatePasswordForm')">修 改</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="邮箱验证" name="second">
          <el-form ref="updatePasswordForm1" :model="updatePasswordForm1" :rules="rules">
            <el-form-item prop="email">
              <el-input v-model.trim="updatePasswordForm1.email" placeholder="请输入邮箱" clearable></el-input>
            </el-form-item>
            <el-form-item prop="imageCode" class="ImageCodeItem">
              <el-input v-model.trim="updatePasswordForm1.imageCode" placeholder="请输入结果" clearable class="CodeInput1"></el-input>
              <el-tooltip class="item" effect="dark" content="点击更换验证码" placement="right">
                <img :src="codeUrl" @click="getCode" class="ImageCode"/>
              </el-tooltip>
            </el-form-item>
            <el-form-item prop="emailCode" class="PhoneCodeItem">
              <el-input  v-model.trim="updatePasswordForm1.emailCode" placeholder="请输入验证码" clearable class="CodeInput1"></el-input>
              <el-button  :disabled="!updatePasswordForm1.show"  @click="getEmailCode" class="codeButton2">
                <span v-show="updatePasswordForm1.show" >发送验证码</span>
                <span v-show="!updatePasswordForm1.show" class="count">{{updatePasswordForm1.count}} s后可点击重发</span>
              </el-button>
            </el-form-item>
            <el-form-item prop="newPassword1">
              <el-input v-model.trim="updatePasswordForm1.newPassword1" placeholder="请设置新密码" clearable show-password></el-input>
            </el-form-item>
            <el-form-item prop="checkNewPass1">
              <el-input v-model.trim="updatePasswordForm1.checkNewPass1" placeholder="再次输入密码" clearable show-password>></el-input>
            </el-form-item>
          </el-form>
          <div class="footerButton">
            <el-button style="width:200px;" @click="updatePasswordE('updatePasswordForm1')">修 改</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
  import $ from 'jquery'
  import {mapMutations} from "vuex";
  const axios = require('axios');
  const TIME_COUNT = 60 // 设置一个全局的倒计时的时间
  export default {
    name: "Login",
    data() {
      let validatePhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号码不可为空'))
        } else {
          if (value !== '') {
            let reg = /^1[345789]\d{9}$/
            if (!reg.test(value)) {
              callback(new Error('请输入格式正确有效的手机号码'))
            }
          }
          callback()
        }
      };

      let validateEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('邮箱不可为空'))
        } else {
          if (value !== '') {
            let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
            if (!reg.test(value)) {
              callback(new Error('请输入格式正确有效的邮箱'))
            }
          }
          callback()
        }
      }

      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registerForm.checkPass !== '') {
            this.$refs.registerForm.validateField('checkPass');
          }
          callback();
        }
      };

      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.registerForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      let validateNewPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.updatePasswordForm.checkPass !== '') {
            this.$refs.updatePasswordForm.validateField('checkPass');
          }
          callback();
        }
      };

      let validateNewPass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.updatePasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      let validateNewPass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.updatePasswordForm1.checkPass !== '') {
            this.$refs.updatePasswordForm1.validateField('checkPass');
          }
          callback();
        }
      };

      let validateNewPass4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.updatePasswordForm1.newPassword1) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        loginForm: {
          username: "",
          password: "",
        },
        registerForm: {
          enterprise: "",
          name: "",
          phone: "",
          email: "",
          code: "",
          password: "",
          checkPass: "",
          imageCode:"",
          imageCodeResult:"",
          phoneCode: "",
          phoneMessageId: "",
          show: true,
          count: 0,
        },
        updatePasswordForm: {
          phone: "",
          imageCode: "",
          phoneCode: "",
          imageCodeResult:"",
          phoneMessageId: "",
          newPassword: "",
          checkNewPass: "",
          show: true,
          count: 0,
        },
        updatePasswordForm1: {
          email: "",
          imageCode: "",
          emailCode: "",
          imageCodeResult: "",
          emailCodeResult: "",
          newPassword1: "",
          checkNewPass1: "",
          createTime: 0,
          show: true,
          count: 0,
        },
        codeUrl: "",
        userToken:'',
        centerDialogVisible: false,
        activeName: "first",
        rules: {
          username:[{
            required: true, message: '请输入用户名', trigger: 'blur'
          }],
          password:[{
            validator: validatePass, trigger: 'blur'
            }],
          checkPass:[{
            validator: validatePass2, trigger: 'blur'
          }],
          newPassword:[{
            validator: validateNewPass, trigger: 'blur'
          }],
          checkNewPass:[{
            validator: validateNewPass2, trigger: 'blur'
          }],
          newPassword1:[{
            validator: validateNewPass3, trigger: 'blur'
          }],
          checkNewPass1:[{
            validator: validateNewPass4, trigger: 'blur'
          }],
          enterprise: [{
            required: true, message: '请输入企业名', trigger: 'blur'
          }],
          name: [{
            required: true, message: '请输入姓名', trigger: 'blur'
          }],
          phone: [{
            validator: validatePhone, trigger: 'blur'
          }],
          email: [{
            validator: validateEmail,trigger: 'blur'
          }],
          imageCode: [{
            required: true, message: '请输入计算结果', trigger: 'blur'
          }],
          phoneCode: [{
            required: true, message: '请输入验证码', trigger: 'blur'
          }],
          emailCode: [{
            required: true, message: '请输入验证码', trigger: 'blur'
          }]
        },
      }
    },
    created () {
      this.getCode()
    },
    methods: {
      ...mapMutations(['changeLogin']),
      loginRes: function(){
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
        this.getCode()
      },
      Login(formName) {
        let v=this;
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            await axios.post("/login", this.loginForm).then(async res => {
              switch (res.data) {
                case 0:
                  this.$message.error({
                    message: '系统不存在该用户喔喵~',
                    center: true
                  });
                  break;
                case 1:
                  this.$message.error({
                    message: '输入的密码是错误的喵~',
                    center: true
                  });
                  break;
                case 2:
                  this.$message.error({
                    message: '该账号被封禁了喵~ 是不是做错事了',
                    center: true
                  });
                  break;
                case 3:
                  this.$message.success({
                    message: '上号!开工了！',
                    center: true
                  });
                  await axios.post("/token", this.loginForm).then(async res => {
                    // console.log(res);
                    v.userToken = res.data.token;
                    // 将用户token保存到vuex中
                    v.changeLogin({token: v.userToken});
                    await axios.post('/getUserMessage', this.loginForm).then(res => {
                      localStorage.setItem('name', res.data.name);
                      localStorage.setItem('username', res.data.username);
                      localStorage.setItem('phone', res.data.phone);
                      localStorage.setItem('id', res.data.id);
                      localStorage.setItem('photo', res.data.photo);
                      localStorage.setItem('department_id', res.data.department_id);
                      localStorage.setItem('employee_id', res.data.employee_id);
                      localStorage.setItem('enterprise_id', res.data.enterprise_id);
                      localStorage.setItem('email', res.data.email);
                      localStorage.setItem('post_id', res.data.post_id);
                      localStorage.setItem('level', res.data.status);
                      // console.log(res);
                    })
                    this.$router.push('/user');
                  })
              }
            })
          } else {
            return false;
          }
        });
      },

      register(formName) {
        let v=this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.registerForm.imageCodeResult != this.registerForm.imageCode) {
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else{
              axios.post("/api/checkMessage",{'messageId':this.registerForm.phoneMessageId,'cacheCode':this.registerForm.phoneCode}).then(res => {
                // console.log(res);
                if(res.data == true){
                  //验证成功
                  axios.post("/register",this.registerForm).then(res => {
                    // console.log(res);
                    switch (res.data) {
                      case 0:
                        this.$message.error({
                          message: '系统已存在该企业了喔喵~',
                          center:true
                        });
                        break;
                      case 1:
                        this.$message.error({
                          message: '该手机号已经存在该系统了喔喵~',
                          center:true
                        });
                        break;
                      case 2:
                        this.$message.error({
                          message: '该邮箱已经存在该系统了喔喵~',
                          center:true
                        });
                        break;
                      case 3:
                        this.$message.error({
                          message: '哼，注册失败了！',
                          center:true
                        });
                        break;
                      case 4:
                        this.$message.success({
                          message: 'yeah~注册成功，开工了！',
                          center:true
                        });
                        axios.post("/token",{'username':this.registerForm.phone,'password':this.registerForm.password}).then(res => {
                          console.log(res);
                          v.userToken = res.data.token;
                          // 将用户token保存到vuex中
                          v.changeLogin({ token:v.userToken});
                          axios.post('/getUserMessage',{'username':this.registerForm.phone}).then(res => {
                            localStorage.setItem('name',res.data.name);
                            localStorage.setItem('username',res.data.username);
                            localStorage.setItem('phone',res.data.phone);
                            localStorage.setItem('id',res.data.id);
                            localStorage.setItem('photo',res.data.photo);
                            localStorage.setItem('department_id',res.data.department_id);
                            localStorage.setItem('employee_id',res.data.employee_id);
                            localStorage.setItem('enterprise_id',res.data.enterprise_id);
                            localStorage.setItem('email',res.data.email);
                            localStorage.setItem('post_id',res.data.post_id);
                            localStorage.setItem('level',res.data.status);
                          })
                          this.$router.push('/user');
                        })
                    }
                  })
                }else{
                  //验证失败或者信息过期
                  this.$message.error({
                    message: '验证码不对或者信息已经过期了喔，再试试吧',
                    center:true
                  });
                }
              })
            }
          }else {
            return false;
          }
        });
      },
      updatePassword(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.updatePasswordForm.imageCodeResult != this.updatePasswordForm.imageCode) {
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else{
              axios.post("/api/checkMessage",{'messageId':this.updatePasswordForm.phoneMessageId,'cacheCode':this.updatePasswordForm.phoneCode}).then(res => {
                // console.log(res);
                if(res.data == true){
                  //验证成功
                  axios.post("/api/updatePassword",this.updatePasswordForm).then(res => {
                    switch (res.data) {
                      case 0:
                        this.$message.error({
                          message: '系统没有该手机号码喔喵~，改不了',
                          center:true
                        });
                        break;
                      case 1:
                        this.$message.success({
                          message: '更新密码成功！赶紧登陆吧喵~',
                          center:true
                        });
                        this.centerDialogVisible = false;
                        this.$refs["updatePasswordForm"].resetFields();
                        this.$refs["updatePasswordForm1"].resetFields();
                        break;
                    }
                  })
                }else{
                  //验证失败或者信息过期
                  this.$message.error({
                    message: '验证码不对或者已经过期了喔，再试试或者重新发送吧',
                    center:true
                  });
                }
              })
            }
            }
        });
      },

      updatePasswordE(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.updatePasswordForm1.imageCodeResult != this.updatePasswordForm1.imageCode) {
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else if(this.updatePasswordForm1.emailCodeResult != this.updatePasswordForm1.emailCode) {
              this.$message.error({
                message: '验证码不对喔喵~',
                center:true
              });
            }else{
                  axios.post("/api/EmailUpdatePassword",this.updatePasswordForm1).then(res => {
                    switch (res.data) {
                      case 0:
                        this.$message.error({
                          message: '系统没有该邮箱喔喵~，改不了',
                          center:true
                        });
                        break;
                      case 1:
                        this.$message.success({
                          message: '更新密码成功！赶紧登陆吧喵~',
                          center:true
                        });
                        this.centerDialogVisible = false;
                        this.$refs["updatePasswordForm"].resetFields();
                        this.$refs["updatePasswordForm1"].resetFields();
                        break;
                      case 2:
                        //信息过期
                        this.$message.error({
                          message: '验证码已经过期了喔，重新发送吧',
                          center:true
                        });
                        break;
                    }
                  })

            }
          }
        });
      },


      getCode () {
      this.$axios.get('/api/getcode').then(resp => {
        if (resp && resp.status === 200) {
          this.codeUrl = resp.data.img
          this.registerForm.imageCodeResult = resp.data.result
          this.updatePasswordForm.imageCodeResult = resp.data.result
          this.updatePasswordForm1.imageCodeResult = resp.data.result
          // console.log(resp.data)
        }
      })
    },
      getPhoneCode() {
        if(this.registerForm.phone === ''){
          this.$message.error({
            message: '请输入手机号码再获取验证码啊喵~',
            center:true
          });
        }else {
          let reg = /^1[345789]\d{9}$/
          if(!reg.test(this.registerForm.phone)) {
            this.$message.error({
              message: '请输入格式正确的手机号码啊喵~',
              center:true
            });
          }else{
            if(this.registerForm.imageCodeResult != this.registerForm.imageCode){
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else{
              this.$axios.post('/api/sendMessage', {
                'phone': this.registerForm.phone
              }).then(res =>  {
                console.log(res);
                if(res.data.success == true) {
                  this.$message.success({
                    message: '我已经给你发送了喔！',
                    center:true
                  });

                  //存入信息ID
                  this.registerForm.phoneMessageId = res.data.messageId;
                }
              })
              // 验证码倒计时
              if (!this.registerForm.timer) {
                this.registerForm.count = TIME_COUNT
                this.registerForm.show = false
                this.registerForm.timer = setInterval(() => {
                  if (this.registerForm.count > 0 && this.registerForm.count <= TIME_COUNT) {
                    this.registerForm.count--
                  } else {
                    this.registerForm.show = true
                    clearInterval(this.registerForm.timer)
                    this.registerForm.timer = null
                  }
                }, 1000)
              }
            }
          }
        }
      },
      getEmailCode () {
        if (this.updatePasswordForm1.email === '') {
          this.$message.error({
            message: '请先输入邮箱再点击获取验证码~',
            center:true
          });
        } else {
          let regemail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!regemail.test(this.updatePasswordForm1.email)) {
            this.$message.error({
              message: '请输入格式正确有效的邮箱号~',
              center:true
            });
          } else {
            if(this.updatePasswordForm1.imageCodeResult != this.updatePasswordForm1.imageCode){
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else{
              this.$axios.post('/api/mail', {
                'email': this.updatePasswordForm1.email
              }).then(res => {
                if(res.data.status == true) {
                  this.$message.success({
                    message: '我已经给你发送了喔！',
                    center:true
                  });
                  this.updatePasswordForm1.emailCodeResult = res.data.data;
                  this.updatePasswordForm1.createTime = res.data.date;
                }
              })
              // 验证码倒计时
              if (!this.updatePasswordForm1.timer) {
                this.updatePasswordForm1.count = TIME_COUNT
                this.updatePasswordForm1.show = false
                this.updatePasswordForm1.timer = setInterval(() => {
                  if (this.updatePasswordForm1.count > 0 && this.updatePasswordForm1.count <= TIME_COUNT) {
                    this.updatePasswordForm1.count--
                  } else {
                    this.updatePasswordForm1.show = true
                    clearInterval(this.updatePasswordForm1.timer)
                    this.updatePasswordForm1.timer = null
                  }
                }, 1000)
              }
            }
            }
        }
      },
      UpdateGetPhoneCode() {
        if(this.updatePasswordForm.phone === ''){
          this.$message.error({
            message: '请输入手机号码再获取验证码啊喵~',
            center:true
          });
        }else {
          let reg = /^1[345789]\d{9}$/
          if(!reg.test(this.updatePasswordForm.phone)) {
            this.$message.error({
              message: '请输入格式正确的手机号码啊喵~',
              center:true
            });
          }else{
            if(this.updatePasswordForm.imageCodeResult != this.updatePasswordForm.imageCode){
              this.getCode();
              this.$message.error({
                message: '输入结果不对喔,再好好算喵~',
                center:true
              });
            }else{
              this.$axios.post('/api/sendMessage', {
                'phone': this.updatePasswordForm.phone
              }).then(res =>  {
                // console.log(res);
                if(res.data.success == true) {
                  this.$message.success({
                    message: '我已经给你发送了喔！',
                    center:true
                  });
                  //存入信息ID
                  this.updatePasswordForm.phoneMessageId = res.data.messageId;
                }
              })
              // 验证码倒计时
              if (!this.updatePasswordForm.timer) {
                this.updatePasswordForm.count = TIME_COUNT
                this.updatePasswordForm.show = false
                this.updatePasswordForm.timer = setInterval(() => {
                  if (this.updatePasswordForm.count > 0 && this.updatePasswordForm.count <= TIME_COUNT) {
                    this.updatePasswordForm.count--
                  } else {
                    this.updatePasswordForm.show = true
                    clearInterval(this.timer)
                    this.updatePasswordForm. timer = null
                  }
                }, 1000)
              }
            }
          }
        }
      },
    }
  }
</script>

<style scoped>
  @import "../assets/css/login.css";
</style>

